package moon

import (
	"github.com/Unixeno/TheMoon/planet/orm"
	"github.com/Unixeno/TheMoon/planet/orm/model"
	"github.com/jinzhu/gorm"
)

type Dao struct {
	model.Moon
	db *gorm.DB
}

func New() Dao {
	return Dao{
		db: orm.DB,
	}
}

func (m *Dao) Create(moon model.Moon) (id string, err error) {
	err = m.db.Create(&moon).Error
	id = moon.ID
	m.db.Create(&model.MoonInfo{
		ID: id,
	})
	return
}

func (m *Dao) List() (moons []model.Moon, err error) {
	moons = make([]model.Moon, 0)
	err = m.db.Find(&moons).Error
	return
}

func (m *Dao) Count(state model.MoonState) (count int) {
	if state == model.MoonAllState {
		m.db.Model(&m.Moon).Count(&count)
	} else {
		m.db.Model(&m.Moon).Where("state = ?", state).Count(&count)
	}
	return
}

func (m *Dao) Delete(moonID string) error {
	// todo: 还需要清理zone
	tx := m.db.Begin()
	affected := tx.Delete(model.Moon{
		ID: moonID,
	}).RowsAffected
	tx.Delete(model.MoonInfo{
		ID: moonID,
	})
	tx.Commit()
	if affected == 0 {
		return gorm.ErrRecordNotFound
	} else {
		return nil
	}
}

func (m *Dao) Get(moonID string) (moon model.Moon, err error) {
	err = m.db.Where("id = ?", moonID).Find(&moon).Error
	return
}

func (m *Dao) Update(moon model.Moon) error {
	return m.db.Save(&moon).Error
}

// 获取当前moon节点的zone状态
func (m *Dao) ListZone() (zones []*model.ZoneMoon, err error) {
	err = m.db.Find(&zones, "moon_id = ?", m.ID).Error
	return
}

// 获取zone目标target 版本
func (m *Dao) ListTargetZone() (zones []*model.Zone, err error) {
	err = m.db.Select("id, zones.version version").
		Joins("join zone_moons on zone_moons.zone_id = zones.id").
		Where("moon_id = ?", m.ID).Find(&zones).Error
	return
}

func (m *Dao) UpdateMoonInfo(info model.MoonInfo) error {
	result := m.db.Model(&model.MoonInfo{ID: m.ID}).Update(&info)
	if result.RowsAffected == 0 {
		return gorm.ErrRecordNotFound
	} else {
		return nil
	}
}

func (m *Dao) GetMoonInfo() (info model.MoonInfo, err error) {
	info.ID = m.ID
	m.db.Take(&info)
	err = m.db.Error
	return
}
